// pages/members/message.js
import evn from "../../utils/http/evn"
const api = require('../../utils/http/api')
Page({
  data: {
    imgBaseUrl: evn.dev.imgUrl,
    messageList: [],
    startX: 0,
    currentIndex: null
  },
  onLoad(options) {
    let userInfo = wx.getStorageSync('userInfo') || {};
    let userId = userInfo.id;
    if (userId) {
      api.apiGetMessageListPublic({ userId }).then(list => {
        console.log('接口原始返回:', list);
        let arr = Array.isArray(list.data) ? list.data : (list.data ? [list.data] : []);
        let now = new Date();
        function getTimeText(timeStr) {
          if (!timeStr) return '';
          // 兼容2025.06.25T22:12:33.500+08:00等格式
          let t = new Date(timeStr.replace(/\./g, '-').replace(/T/, ' ').replace(/\+.*$/, ''));
          if (isNaN(t.getTime())) {
            // 尝试直接new
            t = new Date(timeStr);
          }
          let diff = (now - t) / 1000;
          if (isNaN(diff)) return '';
          if (diff < 60 * 60) {
            let min = Math.floor(diff / 60);
            return min <= 0 ? '刚刚' : `${min}分钟前`;
          } else if (diff < 60 * 60 * 24) {
            let h = Math.floor(diff / 3600);
            return `${h}小时前`;
          } else if (diff < 60 * 60 * 24 * 30) {
            let d = Math.floor(diff / (3600 * 24));
            return `${d}天前`;
          } else if (diff < 60 * 60 * 24 * 365) {
            let m = Math.floor(diff / (3600 * 24 * 30));
            return `${m}月前`;
          } else {
            let y = Math.floor(diff / (3600 * 24 * 365));
            return `${y}年前`;
          }
        }
        let messageList = arr.map(item => ({
          id: item.id, // 用消息本身的id
          objectId: item.objectId || '', // 新增，便于后续跳转
          avatar: item.avatarUrl ? (item.avatarUrl.startsWith('http') ? item.avatarUrl : (item.avatarUrl)) : (evn.dev.imgUrl + '/touxiang.png'),
          action: item.senderAction || '',
          time: item.createdAt ? item.createdAt.split(' ')[0].replace(/-/g, '.') : '',
          timeText: getTimeText(item.createdAt),
          content: item.content || '',
          username: item.userName || '',
          readAt: item.readAt || null,
          offsetX: 0,
          createdAt: item.createdAt // 新增原始时间字段
        }));
        // 按 createdAt 倒序排列
        messageList.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
        console.log('最终messageList:', messageList);
        this.setData({ messageList });
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 自定义返回按钮
   */
  goBack() {
    wx.navigateBack({ delta: 1 });
  },
  updateTimeText() {
    const now = Date.now();
    this.setData({
      messageList: this.data.messageList.map(item => {
        const diff = Math.floor((now - item.time) / 60000);
        let timeText = diff <= 0 ? '刚刚' : `${diff}分钟前`;
        return { ...item, timeText };
      })
    });
  },
  onTouchStart(e) {
    // catchtouchstart 事件 dataset 只在 swiper-row 上有效，需传递 index
    let index = e.currentTarget.dataset.index;
    if (typeof index === 'undefined') {
      // 尝试从父级 swiper-row 获取
      index = e.currentTarget.parentNode && e.currentTarget.parentNode.dataset && e.currentTarget.parentNode.dataset.index;
    }
    if (typeof index === 'string') index = Number(index);
    if (isNaN(index) || index < 0 || index >= this.data.messageList.length) return;
    this.setData({
      startX: e.touches[0].clientX,
      currentIndex: index
    });
  },
  onTouchMove(e) {
    const moveX = e.touches[0].clientX;
    const diffX = moveX - this.data.startX;
    const index = this.data.currentIndex;
    let messageList = this.data.messageList.slice();
    if (typeof index !== 'number' || index < 0 || index >= messageList.length) return;
    if (diffX < 0 && diffX > -75) {
      messageList[index].offsetX = diffX;
    } else if (diffX <= -75) {
      messageList[index].offsetX = -75;
    } else {
      messageList[index].offsetX = 0;
    }
    this.setData({ messageList });
  },
  onTouchEnd(e) {
    const index = this.data.currentIndex;
    let messageList = this.data.messageList.slice();
    if (typeof index !== 'number' || index < 0 || index >= messageList.length) {
      this.setData({ currentIndex: null });
      return;
    }
    if (messageList[index].offsetX <= -40) {
      messageList[index].offsetX = -75;
    } else {
      messageList[index].offsetX = 0;
    }
    this.setData({ messageList, currentIndex: null });
  },
  onDelete(e) {
    const index = Number(e.currentTarget.dataset.index);
    let messageList = this.data.messageList.slice();
    if (isNaN(index) || index < 0 || index >= messageList.length) return;
    const id = messageList[index].id; // 直接用data里的id
    const that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除这条消息吗？',
      success(res) {
        if (res.confirm) {
          api.apiDeleteMessagePublic({ id }).then(resp => {
            if (resp && resp.code === 200) {
              messageList.splice(index, 1);
              that.setData({ messageList });
              wx.showToast({ title: '删除成功', icon: 'success' });
            } else {
              wx.showToast({ title: '删除失败', icon: 'none' });
            }
          }).catch(() => {
            wx.showToast({ title: '删除失败', icon: 'none' });
          });
        }
      }
    });
  },
  onMessageTap(e) {
    let index = e.currentTarget.dataset.index;
    if (typeof index === 'string') index = Number(index);
    if (isNaN(index) || index < 0 || index >= this.data.messageList.length) return;
    let messageList = this.data.messageList.slice();
    const msg = messageList[index];
    // 标记已读
    if (!msg.readAt) {
      api.apiReadMessagePublic({ id: msg.id }).then(resp => {
        if (resp && resp.code === 200) {
          messageList[index].readAt = resp.data || 'read';
          this.setData({ messageList });
        }
      });
    }
    // 跳转到评论详情页面，带上 id（参数名为 id，值为 objectId）
    wx.navigateTo({
      url: '/pages/schools/comments/info?id=' + msg.objectId, 
    });
  },
  stopMove() {
    // 阻止滑动事件冒泡，保证 tap 事件能触发
  },
})